﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using CivilleWP7.CivilleDataServiceReference;
using CivilleWP7.Views.Controls;
using SL.Phone.Federation.Utilities;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;

namespace CivilleWP7.Views.Pages
{
    public partial class SearchTaskResults : PhoneApplicationPage
    {
        private string search;
        private int type;
        private bool IsLightTheme;
        public SearchTaskResults()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SearchTaskResults_Loaded);
            SearchTextBox.KeyDown += new KeyEventHandler(SearchTextBox_KeyDown);

            setBackground();
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if(IsLightTheme)
                myBrush.ImageSource=new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            ContentPanel.Background=myBrush;
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void displayApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
            ApplicationBarIconButton button1;
            if (IsLightTheme)
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Light/appbar.signout.png", UriKind.Relative));
            else
                button1 = new ApplicationBarIconButton(new Uri("/Resources/Icons/Dark/appbar.signout.png", UriKind.Relative));
            button1.Text = "Sign-out";
            button1.Click += new EventHandler(ApplicationBarIconButton_Click);
            ApplicationBar.Buttons.Add(button1);            
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to log out?", "Log out", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RequestSecurityTokenResponseStore _rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
                _rstrStore.RequestSecurityTokenResponse = null;
                NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
            }
        }
        void SearchTaskResults_Loaded(object sender, RoutedEventArgs e)
        {
            TaskListBox.Items.Clear();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            search = NavigationContext.QueryString["search"];
            if (!search.Equals(""))
            {
                PageTitle.Text = search + " Results";
                PopulateTaskListOnSearch();
            }
            try
            {
                type = Int32.Parse(NavigationContext.QueryString["type"]);
                switch (type)
                {
                    case 0:
                        PageTitle.Text = "Search " + search;
                        break;
                    case 1:
                        PageTitle.Text = "Search Carbon " + search;
                        break;
                    case 2:
                        PageTitle.Text = "Search Diamond " + search;
                        break;
                }                
            }
            catch (Exception ex)
            {
                type = 0;
            }
            PopulateTaskListOnSearch();
        }
        private void PopulateTaskListOnSearch()
        {
            CivilleDataServiceConnector.SetTaskQueryParameters(search, type);
            CivilleDataServiceConnector.SearchTaskQuery.BeginExecute(OnSearchTasksQueryComplete, CivilleDataServiceConnector.SearchTaskQuery);
        }
        private void OnSearchTasksQueryComplete(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<Task> query = result.AsyncState as DataServiceQuery<Task>;
                foreach (Task task in query.EndExecute(result))
                {
                    CustomListItem taskCtrl = new CustomListItem();
                    taskCtrl.TitleTxt.Text = task.Title;
                    taskCtrl.DescriptionTxt.Text = task.Description;
                    taskCtrl.ID = task.ID;
                    TaskListBox.Items.Add(taskCtrl);
                    taskCtrl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>((sender, e) =>
                    {
                        TaskDetail.Task = task;
                        NavigationService.Navigate(new Uri("/Views/Pages/TaskDetail.xaml", UriKind.Relative));
                    });
                }
            });
        }
        private void NewSearch()
        {
            TaskListBox.Items.Clear();
            search = SearchTextBox.Text;
            switch(type)
            {
                case 1:
                    PageTitle.Text = "Search Carbon "+search;
                    break;
                case 2:
                    PageTitle.Text = "Search Diamond " + search;
                    break;
                default:
                    PageTitle.Text = "Search " + search;
                    break;
            }            
            PopulateTaskListOnSearch();            
        }
        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NewSearch();
        }

        void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                NewSearch();
                this.Focus();
            }
        }
    }
}
